#include <iostream>
#include <chrono>
#include <thread>
#include <string>
#include <fstream> // 需要包含 fstream
#include "common/config.hpp"
#include "database/db_connection.hpp"
#include "database/file_dao.hpp"
#include "utils/oss_client_manager.hpp"
#include "utils/rabbitmq_client.hpp"
#include "utils/file_utils.hpp" // 建议使用封装好的工具
#include <nlohmann/json.hpp>

using json = nlohmann::json;

void process_message(const std::string& msg) {
    try {
        json msg_json = json::parse(msg);
        std::string hashcode = msg_json.at("hashcode");

        // 1. [修正] 自己构造文件的源路径
        // 从 Config 中获取永久存储目录，并拼接上 hashcode
        std::string source_file_path = Config::UPLOAD_PATH + hashcode;

        std::cout << "[+] Received task. Backing up file: " << source_file_path << std::endl;

        // 2. [修正] 从正确的路径读取文件内容
        // 建议使用您已经封装好的 FileUtils，更简洁
        std::string content = FileUtils::readFile(source_file_path);
        if (content.empty()) {
            std::cerr << "[-] Error: Failed to read source file or file is empty: " << source_file_path << std::endl;
            return;
        }

        // 3. 上传到OSS进行备份 (这部分逻辑不变)
        bool upload_ok = OssClientManager::getInstance()->uploadFile(hashcode, content);
        if (!upload_ok) {
            std::cerr << "[-] Error: Failed to upload to OSS for hash: " << hashcode << std::endl;
            // 在生产环境中，这里应该有重试或记录失败任务的逻辑
            return;
        }
        
        // 4. [修正] 成功备份后，删除本地的永久文件，以节省空间
        // 注意：这是“OSS为主存储”模型的逻辑。如果您想保留本地文件作为主存储，请注释掉这一行。
        // 根据您之前的讨论，我们采用的是“备份”模型，所以这里不删除。
        // remove(source_file_path.c_str());

        std::cout << "[OK] Successfully backed up file to OSS: " << hashcode << std::endl;

    } catch (const json::parse_error& e) {
        std::cerr << "[-] Error: Failed to parse RabbitMQ message. WHAT: " << e.what() << "  MESSAGE: " << msg << std::endl;
    } catch (const json::type_error& e) {
        std::cerr << "[-] Error: JSON key not found. WHAT: " << e.what() << "  MESSAGE: " << msg << std::endl;
    } catch (const std::exception& e) {
        std::cerr << "[-] Error: An unexpected error occurred. WHAT: " << e.what() << std::endl;
    }
}

int main() {
    // 加载配置
    if (!Config::load()) {
        std::cerr << "Error: Failed to load config/app.conf" << std::endl;
        return 1;
    }

    // 初始化数据库连接
    if (!DBConnection::getInstance()->connect()) {
        std::cerr << "Error: Failed to connect to database" << std::endl;
        return 1;
    }

    // 初始化OSS客户端
    OssClientManager::getInstance()->init();
    
    // 初始化RabbitMQ客户端
    RabbitMQClient mq(Config::RABBITMQ_URI, Config::RABBITMQ_EXCHANGE, Config::RABBITMQ_QUEUE, Config::RABBITMQ_ROUTING_KEY);
    
    std::cout << "Transfer service started. Listening for messages..." << std::endl;

    while (true) {
        std::string msg = mq.consume();
        if (!msg.empty()) {
            process_message(msg);
        } else {
            // 如果队列为空，等待1秒，避免CPU空转
            std::this_thread::sleep_for(std::chrono::seconds(1));
        }
    }

    return 0;
}
